package com.sample.springbatch.job.sample.reader;

import com.sample.springbatch.model.FieldJavaType;
import com.sun.beans.editors.IntegerEditor;
import com.sun.beans.editors.LongEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.LineCallbackHandler;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.beans.PropertyEditor;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Flat文件格式读取类  实现了分隔符和json格式
 * Created by zwg on 2017/8/8.
 */
@Component
public class FieldJavaTypeFlatFileItemReader<T> extends FlatFileItemReader {

    Logger logger = LoggerFactory.getLogger(FieldJavaTypeFlatFileItemReader.class);

    public FieldJavaTypeFlatFileItemReader() {
        setResource(new ClassPathResource("jobdata/field_java_type.dat"));
        setLineMapper(new DefaultLineMapper<FieldJavaType>() {{
            setLineTokenizer(new DelimitedLineTokenizer("|") {{  //一行内容分割默认用','分割
                setNames(new String[] { "id", "name","age","birthday"});
                setComments(new String[] { "==","##" });  //# 为默认的注释符号
                setLinesToSkip(1);
            }});

            setFieldSetMapper(new BeanWrapperFieldSetMapper<FieldJavaType>() {{
                setTargetType(FieldJavaType.class);
                //设置字段下划线转驼峰的个数，默认是5
                setDistanceLimit(10);
                //定义特殊的类型转换
                Map<String, PropertyEditor> customerEditorMap = new HashMap<String, PropertyEditor>();
                customerEditorMap.put("java.util.Date", new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
                setCustomEditors(customerEditorMap);
            }});
            setSkippedLinesCallback(new LineCallbackHandler() {
                @Override
                public void handleLine(String s) {
                    logger.error("skip line:"+s);
                }
            });

        }});
    }


}
